package com.ftg.learn.chapter14;


import java.sql.*;
import java.util.*;

/**
 * 封装。返回信息处理
 *  List<Map></Map>
 * @author kangjx
 * @version 1.0
 * @date 2023/3/7 上午8:10
 */
public class LearnJdbc04 {

    public static void main(String[] args) {
        LearnJdbc04 l = new LearnJdbc04();
        List<Map<String,Object>> list = l.queryForList("select sno,sname from student limit ?,?",10,10);
        for (Map<String, Object> map : list) {
            System.out.println(map.get("sno"));
        }
    }

    /**
     * 通用的方法，用来根据指定的sql完成数据操作
     *
     * @param sql  是使用人员传递过来的sql
     *             ex : select sname,sno from student where sno = ?
     * @param para sql未知的参数值
     *             12,"s001"
     * @return List<Map<String, Object>>
     */
    public List<Map<String, Object>> queryForList(String sql, Object... para) {
        List<Map<String, Object>> list = new ArrayList<>();
        try (
                Connection conn = DriverManager.getConnection(JdbcConst.URL, JdbcConst.USERNAME, JdbcConst.PASSWORD);
                PreparedStatement pstm = conn.prepareStatement(sql)
        ) {
            if (Objects.nonNull(para)) {
                for (int i = 0; i < para.length; i++) {
                    pstm.setObject(i + 1, para[i]);
                }
            }
            //结果集
            ResultSet rs = pstm.executeQuery();
            ResultSetMetaData metaData = rs.getMetaData();
            while (rs.next()) {
                Map<String, Object> map = new HashMap<>(metaData.getColumnCount());
                for (int i = 0, len = metaData.getColumnCount(); i < len; i++) {
                    map.put(metaData.getColumnName(i + 1).toLowerCase(), rs.getObject(i + 1));
                }
                list.add(map);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return list;
    }
}
